import Vue from 'vue'
import Vuex from 'vuex'
import { login } from '@/api/sys/login'
import { test } from '@/api/test/test'
import { getTokenFromCookie, setTokenToCookie } from '@/api/utils/auth'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    token: getTokenFromCookie(),
  },
  //mutations里不能写异步操作
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
  },
  //actions用于处理异步操作
  actions: {
    Login({ commit },userInfo){
      const username = userInfo.userName.trim();
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
            if (response.access_token) {
              setTokenToCookie(response.access_token);
                commit('SET_TOKEN', response.access_token);
                resolve();
            }
        }).catch(error => {
          reject(error);
        })
      });
    },
    Register(context){

    },
    Test({ commit }){
      return new Promise((resolve, reject) => {
        test().then(response => {
          resolve();
        }).catch(error => {
          reject(error);
        })
      });
    }
  },
  modules: {

  },
  //
  getters: {
    token: state => state.user.token,
  }
})
